package com.rbac.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.common.Result;
import com.rbac.entity.SysUser;
import com.rbac.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户管理控制器
 *
 * @author rbac-system
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class SysUserController {

    @Autowired
    private SysUserService userService;

    @GetMapping("/page")
    @ApiOperation("分页查询用户")
    @PreAuthorize("hasAuthority('user:query')")
    public Result<IPage<SysUser>> page(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("用户名") @RequestParam(required = false) String username,
            @ApiParam("昵称") @RequestParam(required = false) String nickname,
            @ApiParam("状态") @RequestParam(required = false) Integer status) {
        
        Page<SysUser> page = new Page<>(current, size);
        IPage<SysUser> result = userService.page(page, username, nickname, status);
        return Result.success(result);
    }

    @GetMapping("/list")
    @ApiOperation("查询用户列表")
    @PreAuthorize("hasAuthority('user:query')")
    public Result<List<SysUser>> list() {
        List<SysUser> list = userService.list();
        return Result.success(list);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询用户")
    @PreAuthorize("hasAuthority('user:query')")
    public Result<SysUser> getById(@ApiParam("用户ID") @PathVariable Long id) {
        SysUser user = userService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    @PostMapping
    @ApiOperation("创建用户")
    @PreAuthorize("hasAuthority('user:add')")
    public Result<String> create(@Valid @RequestBody SysUser user) {
        // 检查用户名是否已存在
        if (userService.existsByUsername(user.getUsername())) {
            return Result.error("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (user.getEmail() != null && userService.existsByEmail(user.getEmail())) {
            return Result.error("邮箱已存在");
        }
        
        // 检查手机号是否已存在
        if (user.getPhone() != null && userService.existsByPhone(user.getPhone())) {
            return Result.error("手机号已存在");
        }
        
        boolean success = userService.createUser(user);
        return success ? Result.success("创建成功") : Result.error("创建失败");
    }

    @PutMapping("/{id}")
    @ApiOperation("更新用户")
    @PreAuthorize("hasAuthority('user:edit')")
    public Result<String> update(@ApiParam("用户ID") @PathVariable Long id, @Valid @RequestBody SysUser user) {
        user.setId(id);
        
        // 检查用户名是否已被其他用户使用
        if (userService.existsByUsernameAndIdNot(user.getUsername(), id)) {
            return Result.error("用户名已被其他用户使用");
        }
        
        // 检查邮箱是否已被其他用户使用
        if (user.getEmail() != null && userService.existsByEmailAndIdNot(user.getEmail(), id)) {
            return Result.error("邮箱已被其他用户使用");
        }
        
        // 检查手机号是否已被其他用户使用
        if (user.getPhone() != null && userService.existsByPhoneAndIdNot(user.getPhone(), id)) {
            return Result.error("手机号已被其他用户使用");
        }
        
        boolean success = userService.updateUser(user);
        return success ? Result.success("更新成功") : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    @PreAuthorize("hasAuthority('user:delete')")
    public Result<String> delete(@ApiParam("用户ID") @PathVariable Long id) {
        boolean success = userService.deleteUser(id);
        return success ? Result.success("删除成功") : Result.error("删除失败");
    }

    @PostMapping("/{id}/roles")
    @ApiOperation("分配角色")
    @PreAuthorize("hasAuthority('user:edit')")
    public Result<String> assignRoles(@ApiParam("用户ID") @PathVariable Long id,
                                   @ApiParam("角色ID列表") @RequestBody List<Long> roleIds) {
        boolean success = userService.assignRolesToUser(id, roleIds);
        return success ? Result.success("分配成功") : Result.error("分配失败");
    }

    @PutMapping("/{id}/password")
    @ApiOperation("重置密码")
    @PreAuthorize("hasAuthority('user:edit')")
    public Result<String> resetPassword(@ApiParam("用户ID") @PathVariable Long id,
                                     @ApiParam("新密码") @RequestParam String newPassword) {
        boolean success = userService.resetPassword(id, newPassword);
        return success ? Result.success("密码重置成功") : Result.error("密码重置失败");
    }
}
